package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.WeiXinService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class ApiWeiXinController {
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private PaymentInfoService paymentService;

    @ApiOperation("下单生成二维码")
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable("orderId")Long orderId){
        Map aNativeMap = weiXinService.createNative(orderId);
        return Result.ok(aNativeMap);
    }

  @ApiOperation("查看支付情况")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId")Long orderId){
      //调用查询接口
      Map<String, String> resultMap = weiXinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
      if (resultMap == null) {//出错
          return Result.fail().message("支付出错");
      }
      if ("SUCCESS".equals(resultMap.get("trade_state"))) {//如果成功
          //更改订单状态，处理支付结果
          String out_trade_no = resultMap.get("out_trade_no");
          paymentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
          return Result.ok().message("支付成功");
      }
      return Result.ok().message("支付中");

  }




}
